using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using Mono.Unix.Native;

namespace linenumbers_maarten
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			
			Console.WriteLine("Hello World, this is linenumbers in C# made to run in a mono environment!");
					
			string [] command = new string[3]; //command string array contains the filter command		
			//int [] pipe_in = new int[2];
			//int [] pipe_out = new int[2];
			MainClass main = new MainClass();
			
			
			//check if correct input is given 
			if (args.Length == 1)
			{
				Console.WriteLine("You want to add linenumbers");
				Console.WriteLine("Arguments: {0}", args.Length);				
				command[0] = "cat";
				command[1] = "-n";
				command[2] = args[0];
				main.addNr(command);
			}
			if (args.Length == 2)
			{
				Console.WriteLine("You want to remove linenumbers");
				command[0]= "sed";
				command[1]= "s/^.......//";				
				command[2]= args[1];
				main.remNr(command);
			}
			if (args.Length <1||args.Length>2)
			{
				Console.WriteLine("Wrong arguments given eg: linenumbers.exe [-n] textfile");
				Environment.Exit(1);
			}
			
			
			Console.WriteLine("Linenumbers is finished");          

	
		}
		
		void addNr(string[] command)			
		{
			Console.WriteLine("filter started");
			
			ProcessStartInfo psInfo = new ProcessStartInfo();
			Process runP = new Process();
			FileStream file = new FileStream(command[2], FileMode.Open, FileAccess.Write);
			StreamWriter Swriter = new StreamWriter(file);
			
			psInfo.FileName = command[0];
			psInfo.Arguments = command[1]+" "+command[2];
			psInfo.UseShellExecute = false;
			psInfo.RedirectStandardInput = true;
			psInfo.RedirectStandardOutput = true;
			
			runP.StartInfo = psInfo;
			runP.Start();
			//Console.WriteLine(runP.StandardOutput.ReadToEnd());
			Swriter.Write(runP.StandardOutput.ReadToEnd());
			Swriter.Close();
			runP.WaitForExit();		
		
				
		}	
		
		void remNr(string[] command)
		{
			Console.WriteLine("filter started");
			
			ProcessStartInfo psInfo = new ProcessStartInfo();
			Process runP = new Process();
			FileStream file = new FileStream(command[2], FileMode.Open, FileAccess.ReadWrite);
			StreamReader Sreader = new StreamReader(file);
			StreamWriter Swriter = new StreamWriter(file);
			
			psInfo.FileName = command[0];
			psInfo.Arguments = command[1]+" "+command[2];
			psInfo.UseShellExecute = false;
			psInfo.RedirectStandardInput = true;
			psInfo.RedirectStandardOutput = true;
			
			runP.StartInfo = psInfo;
			runP.Start();
			Console.WriteLine(runP.StandardOutput.ReadToEnd());
			
			Swriter.Close();
			Sreader.Close();
			runP.WaitForExit();
			
		}
		
		
		
}
}